package com.nfit.seckilldemo1.controller;

import com.nfit.seckilldemo1.config.RabbitMQConfig;
import com.nfit.seckilldemo1.pojo.SeckillOrderMessage;
import com.nfit.seckilldemo1.service.impl.SeckillService;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * ClassName:SeckillController
 * Package:com.nfit.seckilldemo1.controller
 * Description
 *
 * @Author L
 * @Create 2025/2/17 19:37
 */
@RestController
@RequestMapping("/api/seckill")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/{skuId}/start")
    public ResponseEntity<?> handleSeckillRequest(
            @PathVariable Long skuId,
            @RequestParam Long userId) {

        // 1. 校验是否重复请求
        if (seckillService.isUserPurchased(userId, skuId)) {
            return ResponseEntity.badRequest().body("您已参与该商品秒杀");
        }

        // 2. Redis预减库存
        int quantity = 1; // 默认秒杀1件
        boolean stockAvailable = seckillService.preReduceStock(skuId, quantity);
        if (!stockAvailable) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("库存不足");
        }

        // 3. 发送MQ消息进行异步下单
        SeckillOrderMessage orderMessage = new SeckillOrderMessage(userId, skuId, quantity);
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.ORDER_QUEUE,
                orderMessage,
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                }
        );

        return ResponseEntity.ok(Map.of("code", 200, "msg", "秒杀请求已进入队列"));
    }

    // 其他接口：查询秒杀结果
    @GetMapping("/result")
    public ResponseEntity<?> getSeckillResult(
            @RequestParam Long userId,
            @RequestParam Long skuId) {
        // 查询Redis或数据库判断订单是否创建成功
        // 此处可返回订单ID或状态
        return ResponseEntity.ok("处理中");
    }
}

